package mylab.demo.usm.biz.service.impl;

import mylab.demo.usm.biz.entity.SysUser;
import mylab.demo.usm.biz.entity.SysUserBinding;
import mylab.demo.usm.biz.mapper.SysUserBindingMapper;
import mylab.demo.usm.biz.mapper.SysUserMapper;
import mylab.demo.usm.biz.service.SysUserService;
import mylab.starters.mybatis.annotation.WriteTransactional;
import mylab.starters.mybatis.template.impl.SuperServiceImpl;
import mylab.usm.api.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Sylar
 * @since 2021-11-24
 */
@Service
public class SysUserServiceImpl extends SuperServiceImpl<String, SysUser, SysUserMapper> implements SysUserService {

    @Autowired
    SysUserBindingMapper userBindingMapper;

    @Override
    public SysUser getByUsername(String username) {
        return baseMapper.getByUsername(username);
    }

    @Override
    public SysUser getByPlatformAndUid(String platformId, String uid) {
        SysUserBinding userBinding = userBindingMapper.getByPlatformAndUid(platformId, uid);
        if (userBinding != null) {
            return baseMapper.selectById(userBinding.getUserId());
        }
        return null;
    }

    @Override
    public boolean validPassword(Long userId, String plainPassword) {
        SysUser user = baseMapper.selectById(userId);
        if (user != null) {
            return PasswordUtil.validPassword(plainPassword, user.getPassword());
        }
        return false;
    }

    @WriteTransactional
    @Override
    public SysUser createUser(SysUserBinding userBinding) {
        SysUser user = getByPlatformAndUid(userBinding.getPlatformId(), userBinding.getUid());
        if (user != null) {
            return user;
        }

        user = new SysUser();
        user.setUsername(userBinding.getPlatformId() + "_" + userBinding.getUsername());
        user.setAvatar(userBinding.getAvatar());
        user.setGender(userBinding.getGender());
        baseMapper.insert(user);

        userBinding.setUserId(user.getId());
        userBindingMapper.insert(userBinding);
        return user;
    }
}
